package com.springcloudalibaba.serviceJournal.rocketmq;

import com.alibaba.fastjson.JSONObject;
import com.springcloudalibaba.bclass.base.BaseMailEntity;
import com.springcloudalibaba.bclass.constant.RocketMqTopicConstant;
import com.springcloudalibaba.bclass.util.ConvertUtils;
import com.springcloudalibaba.bclass.util.LoggerUtil;
import com.springcloudalibaba.serviceJournal.entity.MailEntity;
import com.springcloudalibaba.serviceJournal.service.MailService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.MessageFormat;

/**
 * @描述: 邮件监听器
 * @作者: lixing
 * @日期 2021/6/14 10:17
 */
@Component
@RocketMQMessageListener(
        topic = RocketMqTopicConstant.LOG_TOPIC,                       // topic：和消费者发送的topic相同
        consumerGroup = "MailListener",             // group：不需要和生产者group相同 RocketMqTopicConstant.PROJECTNAME
        selectorExpression = RocketMqTopicConstant.LOG_TAG_MAIL)       // tag: * 表示所有
public class MailListener implements RocketMQListener<BaseMailEntity> {

    @Resource
    private MailService mailService;

    @Override
    public void onMessage(BaseMailEntity baseMailEntity) {
        if (null == baseMailEntity) {
            LoggerUtil.info("MailListener 入参为空");
        } else {
            boolean flag = true;
            try {
                MailEntity mailEntity = ConvertUtils.convert(baseMailEntity, MailEntity.class);
                flag = mailService.save(mailEntity);
                if (!flag) {
                    LoggerUtil.info("MailListener 添加失败");
                }
            } catch (Exception e) {
                flag = false;
                LoggerUtil.info(MessageFormat.format("MailListener 添加出错: {0}", e.getMessage()));
            } finally {
                if (!flag) {
                    LoggerUtil.info(JSONObject.toJSONString(baseMailEntity));
                    LoggerUtil.info("");
                }
            }
        }
    }
}
